package com.srwl.mytx.activity;


import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 移交主题管理权限页面
 */
public class TransferAuthorityActivity extends BaseActivity {

    private static final String TAG = "TransferTopicManger";

    @BindView(R.id.tv_live_room_title)
    TextView tv_liveRoomTitle;

    @BindView(R.id.et_phone)
    EditText etphone;

    @BindView(R.id.btn_search)
    Button btnSearch;

    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;

    @BindView(R.id.tv_username)
    TextView tvUsername;

    @BindView(R.id.btn_confirm)
    Button btnConfirm;

    @BindView(R.id.progress_bar)
    ProgressBar progressBar;

    @BindView(R.id.ll_user)
    LinearLayout ll_user;

    private Topic targetTopic;

    private User targetUser;

    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_surrender_manger);
        targetTopic = getIntent().getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
        ButterKnife.bind(this);
        tv_liveRoomTitle.setText(targetTopic.getTitle());
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchTargetUserInfo();
            }
        });
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (targetUser == null) {
                    showToast(btnConfirm, "请设置移交的用户信息");
                    return;
                }
                ConfirmDialog confirmDialog = new ConfirmDialog(TransferAuthorityActivity.this, "提醒", "确认移交管理权限给[ " + tvUsername.getText() + " ]吗？移交后您将失去管理权限", true);
                confirmDialog.show();
                confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                    @Override
                    public void confirm() {
                        transferAuthority(targetTopic.getId(), targetUser.getuId());
                    }
                });
            }
        });
        btnConfirm.setEnabled(true);

        ll_user.setOnClickListener(v -> {
            if (targetUser != null) {
                UserProfileActivity.startActivity(TransferAuthorityActivity.this, targetUser);
            }
        });
    }

    /**
     * 查找联系人
     */
    private void searchTargetUserInfo() {
        hideSoftKeyboard();
        //获取手机号码
        final String newMangerPhone = etphone.getText().toString();
        //判断是否转给了自己
        if (TextUtils.isEmpty(newMangerPhone)) {
            showToast(etphone, "请输入对方电话号码");
            return;
        }
        String loginPhone = UserProfileManager.getInstance().getLoginUserInfo().getPhone();
        if (TextUtils.equals(newMangerPhone, loginPhone)) {
            showToast(etphone, "不能移交给自己");
            return;
        }
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setCanceledOnTouchOutside(false);
        pd.setMessage("正在查找...");

        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .searchContact(newMangerPhone)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        pd.dismiss();

                        CommonResult commonResult = response.body();
                        if (!response.isSuccessful() || commonResult == null) {
                            Log.d(TAG, response.code() + response.message());
                            showToast(etphone, getString(R.string.system_busy));
                            return;
                        }
                        if (commonResult.isError()) {
                            switch (commonResult.getStatus()) {
                                case Constant.MOBILE_INVALID:
                                    showToast(etphone, "没有对应的用户信息，请检查输入的手机号是否正确");
                                    break;

                                case Constant.PHONE_NUMBER_FORMAT_ERROR:
                                    showToast(etphone, getString(R.string.phone_number_type_error));
                                    break;
                                default:
                                    showToast(etphone, getString(R.string.system_busy));


                            }
                            return;
                        }
                        Object data = commonResult.getData();
                        if (data == null) {
                            return;
                        }
                        JSONObject jsonObject = (JSONObject) data;
                        targetUser = jsonObject.toJavaObject(User.class);
                        showTargetUserInfo();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        pd.dismiss();
                        showToast(etphone, getString(R.string.system_busy));
                    }
                });
    }

    /**
     * 调用服务器端接口完成让度操作
     *
     * @param topicId
     * @param uId
     */
    private void transferAuthority(String topicId, String uId) {
        Map<String, Object> info = new HashMap<>();
        info.put("topicId", topicId);
        info.put("newManagerId", uId);
        progressBar.setVisibility(View.VISIBLE);
        btnConfirm.setEnabled(false);
        RetrofitManager.getInstance()
                .createRequest(TopicService.class)
                .applyTopicAuthorityTransfer(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        btnConfirm.setEnabled(true);
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(btnConfirm, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.PARAMETER_INVALID:
                                    showToast(btnConfirm, "移交的聊天室类型错误");
                                    break;
                                case Constant.DONATION_FORWARD_NO_AUTHORIZATION:
                                    showToast(btnConfirm, "权限不足");
                                    break;
                                default:
                                    showToast(btnConfirm, "系统繁忙,请稍后重试");
                            }
                            return;
                        }

                        showToast("管理权限移交的申请已提交完成");
                        // setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TOPIC, targetTopic));
                        //把新的管理员信息设置进topic,再广播出去
//                        targetTopic.setManagerId(targetUser.getuId());
//                        targetTopic.setManager(targetUser);
//                        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(TransferAuthorityActivity.this);
//                        broadcastManager.sendBroadcast(new Intent(Constant.ACTION_TOPIC_MANAGER_TRANSFER).putExtra(Constant.EXTRA_INFO_TOPIC, targetTopic));
//                        ConfirmDialog confirmDialog = new ConfirmDialog(TransferAuthorityActivity.this, "移交完成", "去看看移交详情？", true);
//                        confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
//                            @Override
//                            public void confirm() {
//                                targetTopic.setManager(targetUser);
//                                startActivity(new Intent(TransferAuthorityActivity.this, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, targetTopic));
//                            }
//                        });
//                        confirmDialog.setCancelListener(new ConfirmDialog.CancelListener() {
//                            @Override
//                            public void cancel() {
//                                showToast("你点击了取消,2s后自动关闭页面");
//                                Handler handler = new Handler();
//                                handler.postDelayed(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        finish();
//                                    }
//                                }, 2000);
//                            }
//                        });
//                        confirmDialog.show();


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        btnConfirm.setEnabled(true);
                        progressBar.setVisibility(View.GONE);
                        Log.i(TAG, "onFailure: " + t.getMessage());
                        showToast("系统错误");
                    }
                });


    }

    /**
     * 前端显示用户信息
     */
    private void showTargetUserInfo() {
        if (targetUser == null) {
            return;
        }
        if (!ll_user.isShown()) {
            ll_user.setVisibility(View.VISIBLE);
        }
        if (targetUser.getUsername() != null) {
            tvUsername.setText(targetUser.getUsername());
        } else {
            tvUsername.setText(targetUser.getNick());
        }

//            String avatarUrl = targetUser.getAvatar();
//            Glide.with(TransferAuthorityActivity.this)
//                    .load(avatarUrl).diskCacheStrategy(DiskCacheStrategy.ALL)
//                    .placeholder(R.drawable.fx_icon_camera)
//                    .into(ivAvatar);

        GlideLoadUtils.glideLoad(this, targetUser.getAvatar(), ivAvatar);

    }

}
